<template>
  <a v-if="!isWideScreen" class="menu-logo" @click="menuHidden = !menuHidden;"></a>
    <header v-if="isWideScreen||menuHidden">
      <el-menu active-text-color="#ffd04b"  class="menu" default-active="2" text-color="#fff">
        <el-menu-item index="2" @click="setToNewThread();selectingModel=false">
          <el-icon><Refresh /></el-icon>
                    <span>创建新聊天</span>
        </el-menu-item>
        <el-sub-menu index="1" style="padding: 0 0;">
          <template #title>
            <el-icon style="color:#4caf50">
              <ChatLineRound />
            </el-icon>
            <span style="color:#4caf50">聊天记录</span>
          </template>
          <div v-for="thread in threads" :key="thread['threadID']" class="message">
            <el-menu-item class="menu-item" :index="thread['threadID'].toString()"
              @click="router.push('/chat/' + thread['threadID']); loadThread(thread['threadID']);selectingModel=false;">
              <span> {{ thread["threadName"] }} </span>
              <el-icon @click.stop="deleteThread(thread['threadID'])"><Delete /></el-icon>
            </el-menu-item>
          </div>

        </el-sub-menu>
        <el-menu-item index="2" @click="selectingModel=!selectingModel">
          <el-icon><Menu /></el-icon>
                    <span>切换模型</span>
        </el-menu-item>
        <el-menu-item index="3">
          <el-icon><InfoFilled /></el-icon>
                    <span>当前模型:</span>
                    <span>{{ ModelNickName }}</span>
        </el-menu-item>
        <el-menu-item index="4" disabled>
          <el-icon>
            <document />
          </el-icon>
          <span>参数调整</span>
        </el-menu-item>
        <el-menu-item index="5" disabled>
          <el-icon>
            <setting />
          </el-icon>
          <span>升级到Bantam plus</span>
        </el-menu-item>
      </el-menu>
    </header>
    <main :style="{ left: isWideScreen ? '200px' : '0', width: isWideScreen ? 'calc(100% - 200px)' : '100%' }">
      <div v-if="selectingModel">
        <NormalChatModelView></NormalChatModelView>
      </div>
      <div class="chat-view-container" v-if="!selectingModel">
        <div v-if="ifNewChatThread" class="default-chat-view">
          <img alt="Vue logo" class="logo" src="@/assets/logo.png" />
          <a class="default-chat-logo-font">Elon musk said : Go ! fuck ! yourself ! </a>
        </div>
        <div v-if="!ifNewChatThread" id="chatview" class="chat-view">
          <div v-for="(message, index) in messages" :key="index" class="message">
            <Message :msg="message.text" :role="message.role === 'assistant' ? ModelNickName : message.role" />
          </div>
        </div>
      </div>

      <div class="InputRegion-container" v-if="!selectingModel">
        <InputRegion @submit="startChat" />
      </div>
    </main>
</template>

<script setup lang="ts">
import InputRegion from "../components/InputRegion.vue";
import Message from "../components/Message.vue";

import { ref, defineComponent, watchEffect, reactive,onMounted } from "vue";
import { ElMenu, ElRow, ElContainer, ElAside } from "element-plus";
import axios from "axios";
import router from "@/router";
import NormalChatModelView from "./NormalChatModelView.vue";
const props = defineProps({
  path: String
});
function GetCookie(name: string) {
  const cookies = document.cookie.split(';');
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim();
    if (cookie.startsWith(name + '=')) {
      return cookie.substring(name.length + 1);
    }
  }
  return '';
}
const isWideScreen = ref(false);
let modelID = 1;
let threadID = 0;
const ModelNickName = ref("ChatGPT")
const ifNewChatThread = ref(true);
const menuHidden = ref(false);
const selectingModel = ref(false);
const messages = reactive<{ role: string; text: string; }[]>([
]);
const threads = reactive<{ threadID: number; threadName: string; }[]>([
]);

isWideScreen.value = window.innerWidth >= 720;

watchEffect(() => {
  const handleResize = () => {
    isWideScreen.value = window.innerWidth >= 720;
  };

  window.addEventListener("resize", handleResize);
  return () => {
    window.removeEventListener("resize", handleResize);
  };
});
onMounted(() => {
  modelID = Number(GetCookie('modelID'));
  getModelNickName(modelID);
});
const loadThread = async (loadthreadID: number) => {
  let csrftoken = GetCookie('csrftoken');
  try {
    const response = await axios.post("/api/v2/normalchatgpt/getnormalthreadbasicinformation", {
      threadID: loadthreadID
    }, {
      headers: {
        'X-CSRFToken': csrftoken // replace 'token' with your token value
      }
    });
    console.log(response.data);
    if (response.data["state"] == "ok") {
      messages.splice(0, messages.length);
      ModelNickName.value = response.data["modelNickName"];
      for (let i = 0; i < response.data["threadMessages"].length; i++) {
        messages.push({
          role: response.data["threadMessages"][i]["role"],
          text: response.data["threadMessages"][i]["content"]
        });
        ifNewChatThread.value = false;
        threadID = loadthreadID;
        console.log("loaded")
      }
    } else {
      console.log("error: " + response.data["msg"]);
    }
  } catch (error) {
    console.error(error);
    // Handle the error here
  }
}
const startChat = async (message: string) => {
  let csrftoken = GetCookie('csrftoken');
  if (ifNewChatThread.value) {
    console.log(message);
    setToNewThread();
    try {
      const response = await axios.post("/api/v2/normalchatgpt/createnormalchats", {
        msg: message,
        modelID: modelID
      }, {
        headers: {
          'X-CSRFToken': csrftoken // replace 'token' with your token value
        }
      });
      console.log(response.data);
      ifNewChatThread.value = false;
      threadID = response.data["threadID"];
      ModelNickName.value = response.data["modelNickName"];
      loadThreaList();
      // Handle the response data here
    } catch (error) {
      console.error(error);
      // Handle the error here
    }
  }
  messages.push({
    role: "user",
    text: message
  });

  try {
    const response = await fetch("/api/v2/normalchatgpt/normalchats", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken // replace 'csrftoken' with your actual CSRF token value
      },
      body: JSON.stringify({
        msg: message,
        threadID: threadID
      })
    });
    messages.push({
      role: "assistant",
      text: ""
    });
    try {
      if (response.body) {
        const reader = response.body?.getReader();
        const decoder = new TextDecoder('utf-8');
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          messages[messages.length - 1]['text'] += decoder.decode(value);
        }
      }
    } catch (error) {
      console.error(error);
      // Handle the error here
    }

  } catch (error) {
    console.error(error);
    // Handle the error here
  }
};
const loadThreaList = async () => {
  let csrftoken = GetCookie('csrftoken');
  try {
    const response = await axios.post("/api/v2/informations/getnormalthreads", {}, {
      headers: {
        'X-CSRFToken': csrftoken // replace 'token' with your token value
      }
    });
    console.log(response.data);
    if (response.data["state"] == "ok") {
      threads.splice(0, threads.length);
      for (let i = 0; i < response.data["threads"].length; i++) {
        threads.push({
          threadID: Number(response.data["threads"][i]["threadID"]),
          threadName: response.data["threads"][i]["threadName"]
        });
        console.log("thread list loaded")
      }

    } else {
      console.log("error: " + response.data["msg"]);
    }
  } catch (error) {
    console.error(error);
    // Handle the error here
  }
}
function setToNewThread() {
  modelID = Number(GetCookie('modelID'));
  ifNewChatThread.value = true;
  getModelNickName(modelID);
  threadID = 0;
  messages.splice(0, messages.length);
  router.push('/chat'); 
}
const deleteThread = async (delThreadID: number) => {
  let csrftoken = GetCookie('csrftoken');
  try {
    const response = await axios.post("/api/v2/informations/delnormalthread", {
      threadID: delThreadID
    }, {
      headers: {
        'X-CSRFToken': csrftoken // replace 'token' with your token value
      }
    });
    console.log(response.data);
    if (response.data["state"] == "ok") {
      loadThreaList();
      if (delThreadID == threadID) {
        setToNewThread();
      }
    } else {
      console.log("error: " + response.data["msg"]);
    }
  } catch (error) {
    console.error(error);
    // Handle the error here
  }
} 
if (props['path'] != '') {
  loadThread(Number(props['path']?.[0]));
} else {
  console.log("new thread");
  ifNewChatThread.value = true;
}
loadThreaList();

const getModelNickName = async (id:number) => {
  if(id<1)
  {
    return;
  }
  let csrftoken = GetCookie('csrftoken');
  try {
    const response = await axios.post("/api/v2/normalchatgpt/getnormalmodelnickname", {
      modelID: id
    }, {
      headers: {
        'X-CSRFToken': csrftoken // replace 'token' with your token value
      }
    });
    console.log(response.data);
    if (response.data["state"] == "ok") {
      ModelNickName.value = response.data["modelNickName"];
    } else {
      console.log("error: " + response.data["msg"]);
    }
  } catch (error) {
    console.error(error);
    // Handle the error here
  }
}
</script>
<style>
@media (prefers-color-scheme: dark) {

  :root {
  --el-menu-hover-bg-color: #yourColor !important;
}

}
</style>
<style scoped>
@media (prefers-color-scheme: light) {
  .menu {
  width: 200px;
  border-width: 0;
  background-color: white;
}
.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
}
}
@media (prefers-color-scheme: dark) {
  .menu {
  width: 200px;
  border-width: 0;
  background-color: #151515;
}
.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #131313;
}
.menu-item:hover {
  background-color: #000000;  /* Change this to your preferred color */
}

.el-menu-item:hover {
  color: yellow;
  /* Change this to your desired hover color */
  background-color: #111111;
}
.el-sub-menu:hover{
  background-color: #111111;

}

}
header {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-end;
  /* Change this from center to flex-end */
  position: fixed;
  bottom: 0;
  left: 0;
  width: 200px;
  height: calc(100% - 70px);
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
  padding: 0;
  z-index: 1000;
  overflow-y:auto;
  scrollbar-width: none; /* For Firefox */

}
header::-webkit-scrollbar {
  display: none; /* For Chrome, Safari and Opera */
}
main {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: fixed;
  bottom: 0;
  left: 200px;
  width: calc(100% - 200px);

  height: calc(100% - 70px);
  /* 添加一些边框和阴影 */
}



.el-menu-item {
  color: #4caf50;
  /* Change this to your desired color */
}



.main {

  width: 100%;
  height: 100%;
}

.menu-logo {
position: fixed;
width: 70px;
height: 70px;
background-color: #00000030;
position: fixed;
  top: 0;
  left: 0;
  z-index: 1000; /* Ensure the icon is above other elements */
}
/* Your existing styles here */
.InputRegion-container {
  width: 90%;
  height: 70px;
  margin: 0 5%;
}

.chat-view-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 92%;
  font-size: 20px;
  color: #999;

  /* Hide scrollbar for Chrome, Safari and Opera */
  ::-webkit-scrollbar {
    display: none;
  }

  /* Hide scrollbar for IE, Edge and Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
  scrollbar-width: none;
  /* Firefox */
}

.default-chat-view {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 92%;
  font-size: 20px;
  color: #999;

}

.chat-view {
  width: 100%;
  height: 92%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  overflow-y: auto;
}

.logo {
  display: block;
  animation: rotate 5s linear infinite;
  width: 15%;
  /* Adjust this value based on your needs */
  height: auto;
  /* Maintain the aspect ratio */
}

.default-chat-logo-font {
  font-size: 3vw;
  font-weight: 500;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: #4caf50;
  text-align: center;
  margin: 0 5%;
  pointer-events: none;
  /* Add this line */
  overflow: hidden;
  /* Ensure the content is clipped */
  white-space: nowrap;
  /* Keep the content on a single line */
  animation: typing 1.5s steps(20, end), .75s step-end infinite;

}


@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes typing {
  from {
    width: 0
  }

  to {
    width: 35%
  }
}

@media (max-width: 600px) {
  .default-chat-view {
    flex-direction: column;
  }
}

/* The typewriter cursor effect */
</style>
